//
//  SliderTap.swift
//  iOSProjectExtensionSwift
//
//  Created by HBGG on 2020/9/3.
//  Copyright © 2020 lidianchao. All rights reserved.
//

import UIKit
protocol SliderTapDelegate: NSObjectProtocol {
    //tabBar选中当前item的代理方法
    func listTabBar(listTabBar:SliderTap,selectIndex:NSInteger)
}
class SliderTap: UIView {
    weak var delegate: SliderTapDelegate?
    private var _currentItemIndex: NSInteger?
    private var _itemsTitle: [String] = []
    private var listButton: UIScrollView?
    private var btnBgView: UIView?
    private var currentSelectedBtn: UIButton?
    private var items: [UIButton] = []
    private var line: UILabel?
    override init(frame: CGRect) {
        super.init(frame: frame)
        initView()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    private func initView() {
        listButton = UIScrollView(frame: CGRect(x: 0, y: 0, width: DeviceWidth, height: self.viewHeight))
        listButton?.showsHorizontalScrollIndicator = false
        self.addSubview(listButton!)
        line = UILabel(frame: CGRect(x: 0, y: 0, width: 0, height: 2))
        line?.backgroundColor = kMainColor
        listButton?.addSubview(line!)
    }
    var currentItemIndex: NSInteger?  {
        get{
            return _currentItemIndex!
        }
        set {
            if(items.count <= 0) {
                return
            }
            _currentItemIndex = newValue
            self.setTitleScrollOffSet(button: items[_currentItemIndex!])
            if (self.delegate != nil) {
                self.delegate!.listTabBar(listTabBar: self, selectIndex: _currentItemIndex!)
            }
            let button = items[_currentItemIndex!]
            button.tag = _currentItemIndex!
            settingSelectedButton(button: button)
            let size = sizeWithFont(fontSize: 15, text: _itemsTitle[_currentItemIndex!])
            line?.frame = CGRect(x: 0, y: button.maxY-2, width: size.width, height: 2)
            line?.center = CGPoint(x: button.center.x, y: button.maxY-1.5)
            refreshLineFrameButton(button: button)
            listButton?.bringSubviewToFront(line!)
        }
    }
    var itemsTitle: [String]? {
        get {
            return _itemsTitle
        } set {
            _itemsTitle = newValue!
            let count = countButtonDeviece()
            var buttonX: CGFloat? = 0
            var buttonW: CGFloat? = 0
            for i in 0..._itemsTitle.count-1 {
                let title = _itemsTitle[i]
                if(_itemsTitle.count>count) {
                    buttonW = DeviceWidth/(CGFloat(count)+0.5)
                } else {
                    buttonW = DeviceWidth/CGFloat(_itemsTitle.count)
                }
                let button = UIButton.createButtonWithTitle(title: title, frame: CGRect(x: buttonX!, y: 0, width: buttonW!, height: self.viewHeight), target: self, action:#selector(itemsDidClick), font: 15, board: false, textColor: ColorWithHex("#333333"))
                if(i == 0) {
                    button.isSelected = true
                }
                listButton?.addSubview(button)
                listButton?.contentSize = CGSize(width: button.maxX, height: self.viewHeight)
                items.append(button)
                buttonX! += buttonW!
            }
        }
    }
    private func countButtonDeviece() -> Int {
        return 4
    }
    @objc private func itemsDidClick(button:UIButton) {
        settingSelectedButton(button: button)
        let index = items.firstIndex(of: button)
        _currentItemIndex = index
        if(self.delegate != nil) {
            self.delegate!.listTabBar(listTabBar: self, selectIndex: index!)
            setTitleScrollOffSet(button: button)
        }
        let size = sizeWithFont(fontSize: 15, text: _itemsTitle[index!])
        line?.frame = CGRect(x: 0, y: button.maxY-2, width: size.width, height: 2)
        line?.center = CGPoint(x: button.center.x, y: button.maxY-1.5)
        refreshLineFrameButton(button: button)
        listButton?.bringSubviewToFront(line!)
    }
    private func setTitleScrollOffSet(button:UIButton) {
        let count = countButtonDeviece()
        if((_currentItemIndex! >= _itemsTitle.count) || (_itemsTitle.count<=countButtonDeviece())) {
            return
        }
        let x1 = button.maxX+DeviceWidth/CGFloat((count+3))-DeviceWidth
        var x = button.maxX+DeviceWidth/(CGFloat(count)+0.5)*2-DeviceWidth
        if(x1 <= 0) {
            x = 0
        }
        listButton?.setContentOffset(CGPoint(x: x, y: 0), animated: true)
        if(_currentItemIndex!+1 != _itemsTitle.count) {
            return
        }
//        let lastButton = items[items.count - 1]
//        if(lastButton.maxX >= )
        
        let n: CGFloat?
        if(_itemsTitle.count > count) {
            n = CGFloat(count)+0.5
        } else {
            n = CGFloat(_itemsTitle.count)
        }
        listButton?.setContentOffset(CGPoint(x: DeviceWidth/n!*CGFloat(_itemsTitle.count+1)-DeviceWidth, y: 0), animated: true)
    }
    private func refreshLineFrameButton(button:UIButton) {
        listButton?.frame = CGRect(x: 0, y: 0, width: DeviceWidth, height: self.viewHeight)
        line!.frame = CGRect(x: 0, y: button.maxY-2, width: 24, height: 2);
        line!.center = CGPoint(x: button.center.x, y: button.maxY-2);
        line!.clipsToBounds = true;
        line!.layer.cornerRadius = 1;
    }
    private func settingSelectedButton(button:UIButton) {
        for view in listButton!.subviews {
            if(view.isKind(of: UIButton.self)) {
                let button1 = view as! UIButton
                button1.isSelected = false
            }
        }
        button.isSelected = true
    }
    private func sizeWithFont(fontSize:CGFloat,text:String) -> CGSize {
        let font = UIFont.init(name: kFontNameLight(), size: fontSize)
        let attribute = [NSAttributedString.Key.font : font]
        let strSize = text.boundingRect(with: CGSize(width: CGFloat(MAXFLOAT), height: 44.0), options: .usesLineFragmentOrigin, attributes: attribute as [NSAttributedString.Key : Any], context: nil).size
        return strSize
    }
    
    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */

}
